﻿using ApprovalFlow.Api.Attributes;
using Autofac;
using Framework.EF.Context;
using Framework.Repository;
using Framework.Utility.Dependency;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;

namespace ApprovalFlow.Api
{
    public class ContextModule : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        { 
            builder.RegisterType<MyDBContext>().AsSelf().InstancePerLifetimeScope(); 
            builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerLifetimeScope();

            Type baseType = typeof(IDependency);
            var assemblieTypes = Assembly.GetEntryAssembly()?.GetReferencedAssemblies()
            .Select(Assembly.Load)
            .SelectMany(c => c.GetExportedTypes())
            .Where(t => baseType.IsAssignableFrom(t))
            .ToArray(); 
            builder.RegisterTypes(assemblieTypes).AsSelf().InstancePerLifetimeScope(); //保证生命周期基于请求

            var assemblies = Assembly.GetEntryAssembly()?//获取默认程序集
                    .GetReferencedAssemblies()//获取所有引用程序集
                    .Select(Assembly.Load)
                    .Where(c => c.FullName!.Contains("Flow.Manage", StringComparison.OrdinalIgnoreCase) || c.FullName!.Contains("Framework.Repository", StringComparison.OrdinalIgnoreCase))
                    .ToArray();
            builder.RegisterAssemblyTypes(assemblies!)
                .Where(type => !type.IsAbstract)
                .AsSelf()   //自身服务，用于没有接口的类
                .AsImplementedInterfaces()  //接口服务
                .PropertiesAutowired()  //属性注入
                .InstancePerLifetimeScope(); //保证生命周期基于请求 

            //支持属性注入
            var controllerBaseType = typeof(ControllerBase);
            builder.RegisterAssemblyTypes(typeof(Program).Assembly)
            .Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType)
            .PropertiesAutowired(new CustomPropertySelector());//支持属性注入
        } 
    }

}
